package com.zbmy.plugin.im.server.core.back.processor;

import java.io.OutputStream;
import java.net.Socket;
import java.nio.ByteBuffer;

import com.zbmy.plugin.im.server.core.protocol.MessageHolder;
import com.zbmy.plugin.im.server.core.protocol.ProtocolHeader;

/**
 * 
 * 消息转发类
 * @ClassName: MessageDispact    
 * @author Yangleping    
 * @date 2018年5月7日 上午11:17:58    
 * @version  v 1.0
 */
public class ShortLinkMessageDispact {
	private final static int BACK_SERVER_PORT = 9109;		// 默认后端服务接口
	
	/**
	 * 
	 * 转发到别的服务器
	 * @author Yangleping
	 * @Title: dispactToOtherServer    
	 * @param remoteIP
	 * @param messageHolder 
	 * @Return: void 返回值
	 */
	@SuppressWarnings("resource")
	public void dispactToOtherServer(String remoteIP, MessageHolder messageHolder) {
		try {
			Socket socket = new Socket(remoteIP, BACK_SERVER_PORT);
			OutputStream os = socket.getOutputStream();
			String content = messageHolder.getBody();
			byte[] array = content.getBytes("UTF-8");
			int byteLen = array.length;
			ByteBuffer directBuffer = ByteBuffer.allocate(byteLen + 9); // 这里一定要注意，分配得大小一定要等于数据占用大小
			directBuffer.putShort(ProtocolHeader.MAGIC);
			directBuffer.put(messageHolder.getSign());
			directBuffer.put(messageHolder.getType());
			directBuffer.put(messageHolder.getStatus());
			directBuffer.putInt(byteLen);
			directBuffer.put(array);
			os.write(directBuffer.array());
			os.flush();
			os.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
